package com.lovetransferjia.chatuidemo.activity;


import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.lovetransferjia.chatuidemo.MyApplication;
import com.lovetransferjia.chatuidemo.R;
import com.lovetransferjia.chatuidemo.jia.utility.ConnectionDetector;
import com.lovetransferjia.chatuidemo.jia.utility.Utility;

import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;
//import com.lovetransferjia.chatuidemo.activity.LoginActivity.Getmyinfo;

public class MainView extends Activity {
	// 屏幕宽度
	public static int screenWidth;
	// 屏幕高度
	public static int screenHeight;
	// 欢迎界面对象
	TextView myWelcome; 
	private SmoothProgressBar mPocketBar;
	
	Handler hd = new Handler() {
		// 重写handleMessage方法
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				// 跳转到welcome_view
				
				break;
			case 1:
				// 跳转到main_view
				goToMainView();
				break;
			
			case 2:
				goToLogin();
				break;
			}
		}
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 去除标题栏
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 去除状态栏
		// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		// WindowManager.LayoutParams.FLAG_FULLSCREEN);
		// 创建DisplayMetrics对象，用于获取屏幕宽度和高度
		setContentView(R.layout.jia_welcome);
		myWelcome=(TextView) findViewById(R.id.welcome_word);
		
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		// 屏幕宽度
		screenWidth = dm.widthPixels;
		MyApplication.screenWidth=screenWidth;
		// 屏幕高度
		screenHeight = dm.heightPixels;
		MyApplication.screenHeight=screenHeight;
		mPocketBar=(SmoothProgressBar) findViewById(R.id.progressBar);
		mPocketBar.setVisibility(View.INVISIBLE);
		ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
		cd.isConnectingToInternet(); // true or false
		go();
		// 发送消息，交由handler处理

	}



	// 跳转到MainView
	private void goToMainView() {
		// 创建Intent对象
		Intent intent = new Intent();
		// Main_view自己创建，就是一个新的activity，此处不坠余
		intent.setClass(this, MainActivity.class);
		intent.putExtra("status","login" );
		// 开始activity跳转
		startActivity(intent);
		// 关闭当前Activity
		this.finish();
	}
	
	private void goToLogin(){
		Intent intent = new Intent();
		// Main_view自己创建，就是一个新的activity，此处不坠余
		intent.setClass(this, LoginActivity.class);
		// 开始activity跳转
		startActivity(intent);
		// 关闭当前Activity
		this.finish();
	}
	

	public void go() {

		// 如果用户名密码都有，直接进入主页面

		String lovenamee = MyApplication.getInstance().getLoveName();
		String lovepwde = MyApplication.getInstance().getLovepwd();
		Log.d("login resume","sss"+lovenamee+lovepwde+MyApplication.getInstance().getUserName()+MyApplication.getInstance().getPassword());
		if (lovenamee != null && lovepwde != null) {
			new LoginTask().execute(lovenamee, lovepwde);
		}else{
			try{
				Thread.sleep(1000);
			}catch (Exception e){
				
			}
			hd.sendEmptyMessage(2);
		}
	}
	static public void autologin(){
		
		String lovenamee = MyApplication.getInstance().getLoveName();
		String lovepwde = MyApplication.getInstance().getLovepwd();
		Log.e("autologin", "love:"+lovenamee+"pwd:"+lovepwde);
		if (lovenamee != null && lovepwde != null) {
			Log.d("auto", "try to autologin");
			new autologinTask().execute(lovenamee, lovepwde);
		}
	}
	
	static public class autologinTask extends AsyncTask<String, Void, Boolean> {
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			Log.d("loginTask","pre");
			
			
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Log.d("loginTask","posts");
			if (result == true) {
				new Getmyinfo().execute();
			}else{
				
				Toast.makeText(MyApplication.applicationContext,failString,Toast.LENGTH_SHORT).show();
			}
		}

		String urlString = MyApplication.baseUrl + "user/login"
				+ MyApplication.postfix;
		String statusString = "", failString = "用户名或密码错误";

		@Override
		protected Boolean doInBackground(String... args) {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("Email", args[0]));
			params.add(new BasicNameValuePair("password", args[1]));

			try {
				JSONObject jsonObject = Utility.PostSimple(urlString, params,
						statusString, failString);
				if (jsonObject.getString("status").equals("success"))
					return true;
				else{
					failString=jsonObject.getString("status");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				failString=e.toString();
			}
			return false;
		}

		
		
	}
	

	 public class LoginTask extends AsyncTask<String, Void, Boolean> {
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			Log.d("loginTask","pre");
			mPocketBar.setVisibility(View.VISIBLE);
			Log.d("loginTask","preend");
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Log.d("loginTask","posts");
			
			if (result = true && MyApplication.id != null) {

				final String username = MyApplication.id;
				final String password = "love" + MyApplication.id;
				EMChatManager.getInstance().login(username, password,
						new EMCallBack() {

							@Override
							public void onSuccess() {
								
								// 登陆成功，保存用户名密码
					
								
									// 进入主页面
							
								hd.sendEmptyMessage(1);
							
							}

							@Override
							public void onProgress(int progress, String status) {

							}

							@Override
							public void onError(int code, final String message) {
								
								runOnUiThread(new Runnable() {
									public void run() {
										
										Toast.makeText(getApplicationContext(),
												"登录失败: " + message, 0).show();
										hd.sendEmptyMessage(2);

									}
								});
							}
						});
			}else{
				mPocketBar.setVisibility(View.INVISIBLE);
				hd.sendEmptyMessage(2);
				Toast.makeText(MyApplication.applicationContext,failString,Toast.LENGTH_SHORT).show();
			}
		}

		String urlString = MyApplication.baseUrl + "user/login"
				+ MyApplication.postfix;
		String statusString = "", failString = "用户名或密码错误";

		@Override
		protected Boolean doInBackground(String... args) {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("Email", args[0]));
			params.add(new BasicNameValuePair("password", args[1]));

			try {
				JSONObject jsonObject = Utility.PostSimple(urlString, params,
						statusString, failString);
				if (jsonObject.getString("status").equals("success")){
					MyApplication.id=jsonObject.getString("id");
					return true;
				}
				else{
					failString=jsonObject.getString("status");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				failString=e.toString();
			}
			return false;
		}

	}

	static public class Getmyinfo extends AsyncTask<String, Void, Boolean> {

		

		@Override
		protected Boolean doInBackground(String... params) {
			Boolean res = Utility.GetUserinfo(0);
			return res;
		}

	}
	
	


}
